package chess;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class GameHall {
	Map<String,Player> playerList = new HashMap<String, Player>();
	Map<String,GameRoom> roomList = new HashMap<String, GameRoom>();
	public void addPlayer(Player player){
		Set<String> set = playerList.keySet();
		Iterator<String> iterator = set.iterator();
		while (iterator.hasNext()) {
			String id = iterator.next();
			Player other = playerList.get(id);
			other.addMSG(new UserListMSG("enter",player.getUsername(),player.getId()));
			player.addMSG(new UserListMSG("enter",other.getUsername(),other.getId()));
		}
		playerList.put(player.getId(),player);
		informPlayer(player);
	}
	public void removePlayer(Player player){
		playerList.remove(player.getId());
		Set<String> set = playerList.keySet();
		Iterator<String> iterator = set.iterator();
		while (iterator.hasNext()) {
			String id = iterator.next();
			Player other = playerList.get(id);
			other.addMSG(new UserListMSG("leave",player.getUsername(),player.getId()));
		}
		
	}
	
	public Player getPlayerById(String id){
		return playerList.get(id);
	}
	
	public GameRoom getRoom(String id){
		GameRoom room = roomList.get(id);
		if(room==null){
			room = new GameRoom(id,this);
			roomList.put(id,room);
		}
		return room;
	}
	
	public void updateRoom(IMSG msg){
		Set<String> set = playerList.keySet();
		Iterator<String> iterator = set.iterator();
		while (iterator.hasNext()) {
			String id = iterator.next();
			Player player = playerList.get(id);
			player.addMSG(msg);
		}
	}
	
	public void informPlayer(Player player){
		Set<String> set = roomList.keySet();
		Iterator<String> iterator = set.iterator();
		while (iterator.hasNext()) {
			String id = iterator.next();
			GameRoom room = roomList.get(id);
			if(room.getSeatA()!=null){
				player.addMSG(new RoomListMSG(room.getId(),"seatA",room.getSeatA()));
			}
			if(room.getSeatB()!=null){
				player.addMSG(new RoomListMSG(room.getId(),"seatB",room.getSeatB()));
			}
			if(room.getStatus()!=null){
				player.addMSG(new RoomListMSG(room.getId(),"status",room.getStatus()));
			}
			
		}
	}
}
